//
//  KADetailViewController.m
//  KeepAccount
//
//  Created by Veer on 2017/12/19.
//  Copyright © 2017年 Veer. All rights reserved.
//

#import "KADetailViewController.h"
#import "KAAccountDetailViewController.h"

#import "KADetailHeaderView.h"
#import "KADetailCell.h"
#import "KADetailSectionHeaderView.h"
#import "VRChooseMonthView.h"

#import "KAAccountSectionModel.h"
#import "KAAccountModel.h"

@interface KADetailViewController () <UITableViewDelegate, UITableViewDataSource, AccountDetailViewControllerDelegate>

@property (nonatomic, weak) KADetailHeaderView *topView;
@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, strong) VRChooseMonthView *chooseDataView;
/** 没有数据提示 */
@property (nonatomic, weak) UIView *nodataView;

@property (nonatomic, strong) NSMutableArray<KAAccountSectionModel *> *accountSectionModelArray;

@end

@implementation KADetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"明细";
//    self.fd_prefersNavigationBarHidden = YES;
    
    self.accountSectionModelArray = [NSMutableArray array];
    
    [self setupHeaderView];
    [self setupSubView];
    
    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
    NSInteger thisYear = components.year;
    NSInteger thisMonth = [components month];
    
    self.topView.year = thisYear;
    self.topView.month = thisMonth;
    [self getAccountDataWithYear:thisYear month:thisMonth];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:kAddAccountNotificationName object:nil];
    
    
    #ifdef ENV_CUSTOM
        NSLog(@"ENV_CUSTOM");
    #elif defined ENV_DEBUG
        NSLog(@"ENV_DEBUG");
    #elif defined ENV_RELEASE
        NSLog(@"ENV_RELEASE");
    #endif
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"1");
    });
    
    NSLog(@"2");
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kAddAccountNotificationName object:nil];
}

- (void)setupHeaderView
{
    
    KADetailHeaderView *topView = [[KADetailHeaderView alloc] init];
    topView.backgroundColor = NAVColor;
    [self.view addSubview:topView];
    self.topView = topView;
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT);
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(68);
    }];
    
    VRChooseMonthView *chooseDataView = [[VRChooseMonthView alloc] init];
    chooseDataView.topMargin = 68 + NAVIGATION_BAR_HEIGHT;
    self.chooseDataView = chooseDataView;
    
    WeakSelf(weakSelf)
    chooseDataView.sureBlock = ^(NSInteger year, NSInteger month) {
      
        weakSelf.topView.year = year;
        weakSelf.topView.month = month;
        [weakSelf getAccountDataWithYear:year month:month];
    };
    
    
    topView.choseMonthBlock = ^{
      
        weakSelf.chooseDataView.year = weakSelf.topView.year;
        weakSelf.chooseDataView.month = weakSelf.topView.month;
        [weakSelf.chooseDataView showOnWindow];
    };
}

- (void)setupSubView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableHeaderView = [[UIView alloc] init];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.estimatedRowHeight = 0;
    tableView.estimatedSectionHeaderHeight = 0;
    tableView.estimatedSectionFooterHeight = 0;
    tableView.sectionHeaderHeight = 0;
    tableView.sectionFooterHeight = 0.01;
    tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CGFLOAT_MIN)];
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CGFLOAT_MIN)];
    tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.topView.mas_bottom);
    }];
    
    UIView *nodataView = [[UIView alloc] init];
    nodataView.hidden = YES;
    [tableView addSubview:nodataView];
    self.nodataView = nodataView;
    [nodataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(tableView);
        make.centerX.mas_equalTo(tableView);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(100);
    }];
    
    UIImageView *nodataImgView = [[UIImageView alloc] init];
    nodataImgView.image = [UIImage imageNamed:@"no_data"];
    [nodataView addSubview:nodataImgView];
    [nodataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.centerX.mas_equalTo(nodataView);
        make.width.mas_equalTo(65);
        make.height.mas_equalTo(65);
    }];
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"暂无数据";
    titleLbl.font = VRFont(14);
    titleLbl.textColor = RGB(214, 214, 214);
    [nodataView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(nodataImgView.mas_bottom).offset(0);
        make.centerX.mas_equalTo(nodataImgView);
    }];
}


#pragma mark - action
- (void)handleNotification:(NSNotification *)notification
{
    [self getAccountDataWithYear:self.topView.year month:self.topView.month];
}


#pragma mark - getdata
- (void)getAccountDataWithYear:(NSInteger)year month:(NSInteger)month
{
    
    [self.accountSectionModelArray removeAllObjects];
    
    NSString *yearStr = [NSString stringWithFormat:@"%ld", year];
    NSString *monthStr = [NSString stringWithFormat:@"%ld", month];
    NSMutableArray *accountModelArray = [[KADataBase sharedDataBase] getAccountModelWithYear:yearStr month:monthStr];
    
    // 是否有数据
    self.nodataView.hidden = accountModelArray.count > 0;
    
    NSString *dateStr = nil;
    double income = 0;
    double expenditure = 0;
    double totalIncome = 0;
    double totalExpenditure = 0;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    for (KAAccountModel *accountModel in accountModelArray) {
        
        if (accountModel.type == 1) {
            totalIncome += accountModel.money;
        }else{
            totalExpenditure += accountModel.money;
        }
        
        KAAccountSectionModel *sectionModel = [self.accountSectionModelArray lastObject];
        if (sectionModel && [sectionModel.date isEqualToString:accountModel.date]) {
            
            if (accountModel.type == 1) {
                income += accountModel.money;
            }else{
                expenditure += accountModel.money;
            }
            sectionModel.income = income;
            sectionModel.expenditure = expenditure;
            [sectionModel.accountModelArray addObject:accountModel];
        }else{
            
            income = 0;
            expenditure = 0;
            if (accountModel.type == 1) {
                income = accountModel.money;
            }else{
                expenditure = accountModel.money;
            }
            KAAccountSectionModel *newSectionModel = [[KAAccountSectionModel alloc] init];
            newSectionModel.date = accountModel.date;
            newSectionModel.income = income;
            newSectionModel.expenditure = expenditure;
            newSectionModel.accountModelArray = [NSMutableArray array];
            [self.accountSectionModelArray addObject:newSectionModel];
            [newSectionModel.accountModelArray addObject:accountModel];
            
            // 日期格式化转换
            formatter.dateFormat = @"yyyy-MM-dd";
            NSDate *date = [formatter dateFromString:accountModel.date];
            formatter.dateFormat = @"MM月dd日 EEEE";
            newSectionModel.formatDate = [formatter stringFromDate:date];
        }
    }
    
    // 设置topView的金额
    self.topView.income = totalIncome;
    self.topView.expenditure = totalExpenditure;
    
    [self.tableView reloadData];
    NSLog(@"xxx");
}


//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
//{
//    UIViewController *vc = [[UIViewController alloc] init];
//    vc.view.backgroundColor = [UIColor whiteColor];
//    [self.navigationController pushViewController:vc animated:YES];
//}


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.accountSectionModelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    KAAccountSectionModel *sectionModel = self.accountSectionModelArray[section];
    
    KADetailSectionHeaderView *headerView = [KADetailSectionHeaderView headerViewWith:tableView];
    headerView.accountSectionModel = sectionModel;
    return headerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    KAAccountSectionModel *sectionModel = self.accountSectionModelArray[section];
    
    return sectionModel.accountModelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [UIView new];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    KAAccountSectionModel *sectionModel = self.accountSectionModelArray[indexPath.section];
    KAAccountModel *accountModel = sectionModel.accountModelArray[indexPath.row];
    
    KADetailCell *cell = [KADetailCell cellWith:tableView];
    cell.accountModel = accountModel;
    if (indexPath.section == 3 - 1 && indexPath.row == 5 - 1) {
        cell.lineType = LineTypeBottom;
    }else if (indexPath.row == 5 - 1){
        cell.lineType = LineTypeCenterAndBottom;
    }else{
        cell.lineType = LineTypeCenter;
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    BOOL isNotShowDetail = [[NSUserDefaults standardUserDefaults] boolForKey:kShowDetailSwitchIsCloseKey];
    if (isNotShowDetail) {
        return;
    }
    
    KAAccountSectionModel *sectionModel = self.accountSectionModelArray[indexPath.section];
    KAAccountModel *accountModel = sectionModel.accountModelArray[indexPath.row];
    
    KAAccountDetailViewController *accountDetailVc = [[KAAccountDetailViewController alloc] init];
    accountDetailVc.accountModel = accountModel;
    [self.navigationController pushViewController:accountDetailVc animated:YES];
}


#pragma mark - AccountDetailViewControllerDelegate
- (void)accountDetailViewControllerEditDidFinished
{
    [self getAccountDataWithYear:self.topView.year month:self.topView.month];
}

@end
